import BaseButton from '@/components/base/BaseButton';
import BaseForm, {
  BaseFormSelect,
  BaseFormText,
  BaseFormTextArea,
  ProFormInstance
} from '@/components/base/BaseForm';
import BasePageFrame from '@/components/base/BasePageFrame';
import { getUserInfo } from '@/services/global';
import useUserStore from '@/store/user';
import { useRequest } from '@/utils/request';
import { EditOutlined } from '@ant-design/icons';
import { Card, Space, Spin, Tag } from 'antd';
import { useRef, useState } from 'react';
import { getList } from '../../radar/ServerAreaInfo/api';
import { UserModel } from '../data';
import { editUser } from '../UserInfo/api';

const Profile = () => {
  const [mode, setMode] = useState<'read' | 'edit'>('read');
  const { userinfo, setUser } = useUserStore();
  const save = useRequest(editUser, { manual: true });
  const formRef = useRef<ProFormInstance>();
  const user = useRequest(getUserInfo, {
    onSuccess(data) {
      setUser(data);
      formRef.current?.setFieldsValue(data);
    }
  });
  return (
    <BasePageFrame>
      <Card style={{ height: '100%' }}>
        <div style={{ paddingLeft: '10%' }}>
          <Spin spinning={user.loading}>
            <BaseForm<UserModel>
              formRef={formRef}
              initialValues={userinfo}
              labelCol={{ style: { width: 80 } }}
              layout='horizontal'
              style={{ width: 560 }}
              submitter={{
                render: (props) => {
                  return mode === 'read' ? (
                    <BaseButton
                      type='primary'
                      icon={<EditOutlined />}
                      onClick={() => {
                        setMode('edit');
                      }}
                    >
                      编辑
                    </BaseButton>
                  ) : (
                    <Space>
                      <BaseButton type='primary' loading={save.loading} onClick={props.submit}>
                        确定
                      </BaseButton>
                      <BaseButton
                        onClick={() => {
                          props.reset();
                          setMode('read');
                        }}
                      >
                        取消
                      </BaseButton>
                    </Space>
                  );
                }
              }}
              onFinish={async (values) => {
                values.userType = userinfo.userType as UserModel['userType'];
                values.jobName = userinfo.jobName;
                values.id = userinfo.userId;
                if (userinfo.username !== 'admin') {
                  values.areaId = userinfo.area.map((i) => i.areaId);
                }
                const ok = await save.run(values);
                if (ok) {
                  user.run();
                  setMode('read');
                }
              }}
            >
              <BaseFormText
                proFieldProps={{ mode }}
                label='用户名'
                name='username'
                rules={[{ required: mode === 'edit', message: '请输入用户名' }]}
              />
              <BaseFormText
                proFieldProps={{ mode }}
                label='真实姓名'
                name='realName'
                rules={[{ required: mode === 'edit', message: '请输入真实姓名' }]}
              />
              <BaseFormText
                proFieldProps={{ mode }}
                label='邮箱'
                name='mailbox'
                fieldProps={{ maxLength: 50 }}
                rules={[
                  { required: mode === 'edit', message: '请输入用户邮箱' },
                  {
                    pattern:
                      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                    message: '请输入正确格式的邮箱信息'
                  }
                ]}
              />
              <BaseFormText
                proFieldProps={{ mode }}
                label='联系方式'
                name='mobile'
                rules={[
                  { required: mode === 'edit', message: '请输入联系方式' },
                  {
                    pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
                    message: '请输入正确格式的联系方式，仅支持手机号'
                  }
                ]}
              />
              {userinfo.username === 'admin' ? (
                <BaseFormSelect
                  label='服务区域'
                  name='areaId'
                  placeholder='请选择服务区域'
                  rules={[{ required: true, message: '请选择服务区域' }]}
                  request={getList}
                  readonly={mode === 'read'}
                  fieldProps={{
                    fieldNames: {
                      label: 'name',
                      value: 'id'
                    },
                    defaultSelectedOptions: user.data?.area.map((i) => ({
                      name: i.areaName,
                      id: i.areaId
                    }))
                  }}
                />
              ) : (
                <BaseFormText
                  proFieldProps={{
                    mode: 'read',
                    render: (data: UserModel['area'] = []) => {
                      return data.map((i) => <Tag key={i.areaId}>{i.areaName}</Tag>);
                    }
                  }}
                  label='服务区域'
                  name='area'
                />
              )}
              <BaseFormText
                proFieldProps={{ mode }}
                label='证件'
                name='certificatesId'
                rules={[
                  {
                    pattern:
                      /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
                    message: '请输入正确格式的身份证信息'
                  }
                ]}
              />
              <BaseFormTextArea proFieldProps={{ mode }} label='个人备注' name='remarks' />
            </BaseForm>
          </Spin>
        </div>
      </Card>
    </BasePageFrame>
  );
};

export default Profile;
